<template>
  <div class="arcgis-wrapper relative">
    <!-- <div class="handle-list flex flex-wrap align-content-around">
      <a-button @click="handleImportXls" type="primary" icon="upload"></a-button>
      <a-button @click="handleExportTestXls" type="primary" icon="cloud-download"></a-button>
      <j-import-modal ref="importModal" @ok="importOk" v-model="fileList"></j-import-modal>
    </div> -->
    <base-map class="all-container" :current="currentKey" @sendMap="getMap" :dataSources="dataSources" />
  </div>
</template>

<script>
/* eslint-disable */
import baseMap from './baseMap'
import JImportModal from '@/views/components/JImportModal.vue'
import { axios } from '@/utils/request'
import * as turf from '@turf/turf'
import * as XLSX from 'xlsx/xlsx.mjs'
import * as cptable from 'xlsx/dist/cpexcel.full.mjs'
import X2js from 'x2js'
import proj4 from 'proj4'
import { mapState } from 'vuex'
export default {
  name: 'arcgis',
  components: { baseMap, JImportModal },
  data() {
    return {
      fileList: [],
      handleList: [
        {
          title: '切换底图',
          icon: 'toggle'
        },

        {
          title: '绘制点',
          icon: 'multipoint'
        },
        {
          title: '绘制线',
          icon: 'line'
        },
        {
          title: '绘制面',
          icon: 'extent'
        },
        {
          title: '清除',
          icon: 'clear'
        },
        {
          title: '测量',
          icon: 'distance'
        },
        {
          title: '打点',
          icon: 'addPoint'
        },
        {
          title: '加载地图服务',
          icon: 'mapServer'
        },
        {
          title: '轨迹',
          icon: 'trajectory'
        }
      ],
      header: [],
      columns: [],
      dataSources: [],
      exportData: [],
      currentKey: '',
      tb: '',
      map: ''
    }
  },
  watch: {
    fileList: {
      deep: true,
      handler(val) {
        // this.getExcel()
      }
    }
  },
  created() {
    axios({
      baseURL: '/',
      url: '/data/GetAllDictByTableSpace.json',
      method: 'get'
    }).then(
      (res) => {
        let x2js = new X2js()
        // 将xml解析为我们需要的json对象
        let json = x2js.xml2js(res.d)
        this.jsonDict = json.Result.Table
        console.log(json)
      },
      (err) => {
        console.log(err)
      }
    )
  },
  methods: {
    handleImportXls() {
      this.$refs.importModal.show()
    },
    importOk(fileName) {
      this.fileName = fileName
      this.getExcel()
    },
    getExcel() {
      this.readExcel(this.fileList[0]).then((workbook) => {
        this.properties = this.jsonDict.filter((item) => {
          return item._ID == 'YW_PIPEDEFECTS'
        })
        this.properties.map((table, idx) => {
          if (table._ID == 'YW_PIPEDEFECTS') {
            this.columns = table.Field
            const exlname = workbook.SheetNames[0]
            const ws = workbook.Sheets[exlname]
            this.columns.sort((a, b) => {
              return parseInt(a._Order) - parseInt(b._Order)
            })
            var range = XLSX.utils.decode_range(ws['!ref'])
            //for (R = r.s.r + offset; R <= r.e.r; ++R)
            for (var C = range.s.c; C <= range.e.c; ++C) {
              var coord = XLSX.utils.encode_cell({ r: 0, c: C }),
                cell = ws[coord]
              if (!cell || !cell.v) continue
              // clean up raw value of string cells
              if (cell.t == 's') cell.v = cell.v.trim().replace(/\r\n/g, '').replace(/\n/g, '')

              // clean up formatted text
              if (cell.w) cell.w = cell.w.trim().replace(/\r\n/g, '').replace(/\n/g, '')
              this.header[C] = cell.v
            }
            this.header.push('ZZYY')
            this.header.push('X_1')
            this.header.push('Y_1')
            this.filterHeader = []
            this.exportHeader = this.columns.map((column) => {
              let description = column._Description
              if (
                typeof column._Description == 'string' &&
                description.trim() != '' &&
                description.indexOf('//') >= 0
              ) {
                description = description.substring(2)
                let strArr = description.split(';').map((string) => {
                  return string.split('-').reverse()
                })
                column._Description = Object.fromEntries(strArr)
              }
              if (['JCFS', 'QXLX', 'CZ', 'RANK', 'JCFX', 'SHAPETYPE'].includes(column._ID)) {
                this.filterHeader.push(column)
              }
              return column._ID
            })
            console.log(this.filterHeader)
            let opts = {
              blankrows: false,
              defval: null
            }
            const exl = XLSX.utils.sheet_to_json(ws, opts)
            var epsg4490 = '+proj=longlat +ellps=GRS80 +no_defs'
            var webMercator =
              '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext  +no_defs'
            var cgcs30007 = '+proj=tmerc +lat_0=0 +lon_0=118.5 +k=1 +x_0=500000 +y_0=0 +ellps=GRS80 +units=m +no_defs'
            var cgcs2000 = '+proj=tmerc +lat_0=0 +lon_0=120 +k=1 +x_0=500000 +y_0=0 +ellps=GRS80 +units=m +no_defs'
            this.dataSources = []
            this.exportData = []
            var obj = {}
            this.header.map((field) => {
              obj[field] = ''
            })
            for (var i = 0; i < 5; i++) {
              this.exportData.push(obj)
            }
            exl.map((row) => {
              if (
                row.X &&
                row.Y &&
                row.X1 &&
                row.Y1 &&
                row.X != '#N/A' &&
                row.X1 != '#N/A' &&
                row.Y1 != '#N/A' &&
                row.Y != '#N/A'
              ) {
                var obj = {}
                if (row.JCSJ instanceof Date) {
                  var dateString = row.JCSJ.toJSON().substr(0, 10)
                  row.JCSJ = dateString.replace(/\//g, '-')
                } else {
                  row.JCSJ = row.JCSJ && row.JCSJ.replace(/\//g, '-')
                }
                //
                //row.JCFS = parseInt(this.JCFSObj._Description[row.JCFS])
                this.filterHeader.map((column) => {
                  if (!column._Description[row[column._ID]]) {
                    row[column._ID] = column._Description['其他'] || column._Description['其它'] || 0
                  } else {
                    row[column._ID] = parseInt(column._Description[row[column._ID]])
                  }
                })
                var sLngLat = proj4(cgcs30007, epsg4490, [Number(row.X), Number(row.Y)])
                var eLngLat = proj4(cgcs30007, epsg4490, [Number(row.X1), Number(row.Y1)])
                var line = turf.lineString([sLngLat, eLngLat])
                var options = { units: 'kilometers' }
                var geoFeature = turf.along(line, row.QWZ / 1000, options)
                var cutPoi = proj4(epsg4490, cgcs30007, geoFeature.geometry.coordinates)
                row.X_1 = cutPoi[0]
                row.Y_1 = cutPoi[1]
                Object.assign(obj, row)
                row.proj_s = proj4(cgcs30007, webMercator, [Number(row.X), Number(row.Y)])
                row.proj_e = proj4(cgcs30007, webMercator, [Number(row.X1), Number(row.Y1)])
                row.proj_t = proj4(epsg4490, webMercator, geoFeature.geometry.coordinates)
                this.exportData.push(obj)
                this.dataSources.push(row)
              }
              return row
            })
            console.log(this.dataSources)
          }
        })
      })
    },
    parseExcel() {
      this.readExcel(this.fileList[0]).then((workbook) => {
        this.properties = this.jsonDict.filter((item) => {
          return workbook.SheetNames.includes(item._ID)
        })
        this.panes = []
        this.properties.map((item, idx) => {
          let pane = {}
          pane.title = item._Label
          pane.key = idx
          pane.name = item._ID
          const ws = workbook.Sheets[item._ID]
          const exl = XLSX.utils.sheet_to_json(ws)
          if (exl.length == 0) {
            return
          }
          item.Field.sort((a, b) => {
            return parseInt(a._Order) - parseInt(b._Order)
          })
          var range = XLSX.utils.decode_range(ws['!ref'])
          //for (R = r.s.r + offset; R <= r.e.r; ++R)
          let firstRow = []
          for (var C = range.s.c; C <= range.e.c; ++C) {
            var coord = XLSX.utils.encode_cell({ r: 0, c: C }),
              cell = ws[coord]
            firstRow.push(cell.v)
          }
          let columns = []
          item.Field.map((property) => {
            if (firstRow.includes(property._ID)) {
              let column = {
                title: property._Label,
                id: property._Order,
                width: '80px',
                ellipsis: true,
                dataIndex: property._ID,
                scopedSlots: { customRender: property._ID }
              }
              columns.push(column)
            }
          })
          pane.columns = columns
          pane.dataSource = []
          if (item._ID == 'YW_PIPEDEFECTS') {
            var epsg4490 = '+proj=longlat +ellps=GRS80 +no_defs'
            var webMercator =
              '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext  +no_defs'
            var cgcs30007 = '+proj=tmerc +lat_0=0 +lon_0=118.5 +k=1 +x_0=500000 +y_0=0 +ellps=GRS80 +units=m +no_defs'
            var cgcs2000 = '+proj=tmerc +lat_0=0 +lon_0=120 +k=1 +x_0=500000 +y_0=0 +ellps=GRS80 +units=m +no_defs'
            pane.dataSource = exl.map((row) => {
              var sLngLat = proj4(cgcs30007, epsg4490, [Number(row.X), Number(row.Y)])
              var eLngLat = proj4(cgcs30007, epsg4490, [Number(row.X1), Number(row.Y1)])
              var line = turf.lineString([sLngLat, eLngLat])
              var options = { units: 'kilometers' }
              var geoFeature = turf.along(line, row.QWZ / 1000, options)
              console.log(geoFeature.geometry.coordinates)
              var cutPoi = proj4(epsg4490, cgcs30007, geoFeature.geometry.coordinates)
              row.targetX = cutPoi[0]
              row.targetY = cutPoi[1]
            })
          }
          pane.ipagination = {
            pageSize: 10,
            showTotal: (total, range) => {
              return range[0] + '-' + range[1] + ' 共' + total + '条'
            },
            total: pane.dataSource.length
          }
          this.panes.push(pane)
        })
      })
    },
    readExcel(file, properties) {
      return new Promise(function (resolve, reject) {
        // 返回Promise对象
        const reader = new FileReader()
        reader.onload = (e) => {
          // 异步执行
          try {
            // 以二进制流方式读取得到整份excel表格对象
            const data = e.target.result
            const workbook = XLSX.read(data, { type: 'binary', codepage: 936, cellDates: true, cellFormula: true })
            resolve(workbook)
          } catch (e) {
            reject(e.message)
          }
        }
        reader.readAsBinaryString(file)
      })
    },
    handleExportTestXls() {
      this.columns.sort((a, b) => {
        return parseInt(a._Order) - parseInt(b._Order)
      })

      if (this.exportData.length > 0) {
        // 创建工作簿
        const wb = XLSX.utils.book_new()
        const sheet = XLSX.utils.json_to_sheet(this.exportData, { header: this.exportHeader })
        let range = XLSX.utils.decode_range(sheet['!ref'])
        this.columns.map((column, idx) => {
          let idxOf = this.exportHeader.indexOf(column._ID)
          if (idxOf > -1) {
            var coord = XLSX.utils.encode_cell({ r: 1, c: idxOf })
            sheet[coord] = { t: 's', v: column._Label }
            var coord = XLSX.utils.encode_cell({ r: 3, c: idxOf })
            sheet[coord] = { t: 's', v: idx }
          }
        })
        XLSX.utils.book_append_sheet(wb, sheet, 'YW_PIPEDEFECTS')
        // 生成文件并下载
        XLSX.writeFile(wb, this.fileName.substring(0, this.fileName.lastIndexOf('.')) + '缺陷.xlsx', {
          cellDates: true,
          cellFormula: true
        })
      }
    },
    changeHandle(val) {
      if (val == 'clear') {
        this.map.graphics.clear()
        return
      } else if (val == 'trajectory') {
        this.$message.info('功能开发中...')
        return
      } else if (val == 'multipoint' || val == 'line' || val == 'extent') {
        this.tb.activate(val)
        this.map.disableMapNavigation()
      } else if (val == 'addPoint') {
        this.addPoint()
      } else if (val == 'mapServer') {
        this.addMapServer()
      }
      this.currentKey = val
    },

    getMap(map, tb) {
      this.map = map
      this.tb = tb
      this.tb.on('draw-end', (evt) => {
        this.tb.deactivate()
        this.map.enableMapNavigation()
        let symbol = this.getDrawStyle(this.currentKey)
        this.map.graphics.add(new esri.Graphic(evt.geometry, symbol))
        evt.geometry.setCacheValue('geoShape', this.currentKey)
        this.currentKey = ''
      })
    },

    getDrawStyle(key) {
      if (key == 'multipoint') {
        /* eslint-disable */
        var symbol = new esri.symbol.SimpleMarkerSymbol()
        symbol.setColor(new esri.Color('#00FFFF'))
        return symbol
      } else if (key == 'line') {
        let CartographicLineSymbol = esri.symbol.CartographicLineSymbol
        return new CartographicLineSymbol(
          CartographicLineSymbol.STYLE_SOLID,
          new esri.Color([255, 0, 0]),
          2,
          CartographicLineSymbol.CAP_ROUND,
          CartographicLineSymbol.JOIN_MITER,
          5
        )
      } else {
        let SimpleFillSymbol = esri.symbol.SimpleFillSymbol
        let SimpleLineSymbol = esri.symbol.SimpleLineSymbol
        return new SimpleFillSymbol(
          SimpleFillSymbol.STYLE_SOLID,
          new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new esri.Color([255, 0, 0]), 1),
          new esri.Color([255, 0, 0, 0.1])
        )
      }
    },

    addPoint() {
      const pointArr = [
        {
          x: 116.413384,
          y: 39.910925
        },
        {
          x: 117.209523,
          y: 39.093668
        },
        {
          x: 113.306436,
          y: 40.082469
        },
        {
          x: 109.787443,
          y: 39.614482
        },
        {
          x: 123.567539,
          y: 41.849226
        },
        {
          x: 129.63954,
          y: 44.556246
        },
        {
          x: 121.480539,
          y: 31.235929
        },
        {
          x: 121.628572,
          y: 29.866033
        },
        {
          x: 114.311582,
          y: 30.598467
        },
        {
          x: 103.679433,
          y: 30.636596
        }
      ]
      let current = pointArr[parseInt(Math.random(0, 0.9) * 10)]
      let point = new esri.geometry.Point(current.x, current.y, new esri.SpatialReference({ wkid: 4326 }))
      let path = require('../../../assets/map/point.png')
      let symbol = new esri.symbol.PictureMarkerSymbol(path, 25, 25)
      let graphics = new esri.Graphic(point, symbol, '')
      this.map.graphics.add(graphics)
      this.map.centerAndZoom(point, 8)
      this.currentKey = ''
    },

    addMapServer() {
      let mapLayer = new esri.layers.ArcGISDynamicMapServiceLayer(
        'http://cache1.arcgisonline.cn/arcgis/rest/services/ChinaOnlineCommunity_Mobile/MapServer'
      )
      this.map.addLayer(mapLayer)
      let point = new esri.geometry.Point(116.413384, 39.910925, new esri.SpatialReference({ wkid: 4326 }))
      this.map.centerAndZoom(point, 4)
    }
  }
}
</script>
<style lang="less" scoped>
.arcgis-wrapper {
  width: 100%;
  height: 100%;
  .handle-list {
    position: absolute;
    right: 15px;
    top: 15px;
    height: auto;
    width: auto;
    text-align: center;
    padding: 5px;
    /*background: rgba(48, 65, 86, 0.8);*/
    z-index: 99;
    .handle-item {
      width: 100%;
    }
    button {
      margin-right: 8px;
    }
  }
}
</style>
